ActiveAdmin.register Scan do

    actions :all, :except => [:edit]
    menu :priority => 2, :label => "Scan"

    index :download_links => false do
        column :scan_name
        column :system
        column(t("scans.form.created")){|scan|
          now = Time.now
          created = scan.created_at

          time = now - created
          created_at = (time.to_i / 60)

          if created_at >= 60
            if created_at >= 60 and created_at < 120 
              created_at = (created_at.to_i / 60).to_s + " hour ago"
            elsif created_at >= 1440
              created_at = (created_at.to_i / 1440).to_s + " days ago"
            else
              created_at = (created_at.to_i / 60).to_s + " hours ago"
            end
          else
            created_at = created_at.to_i.to_s + " minutes ago"
          end

          created_at
        }

        default_actions
    end

   form :remote => true do |f|
        f.inputs t("scans.form.title") do
            f.input :scan_name, :label => t("scans.form.scan_name")
            f.input :profile, :as => :select, :collection => Profile.all.map {|p| [p.profile, p.id]}, :include_blank => true, :label => t("scans.form.profile")
            f.input :system, :label => t("scans.form.systems")
            
            f.buttons :submit, :class => "buttons_fieldset"
        end
   end
   
   controller do
     def create

        systems = params[:scan][:system]
        profile = params[:scan][:profile]
        scan_name = params[:scan][:scan_name]

        @profile = Profile.find(profile)
    
        scan_type = @profile.scantype

        r = Random.new
        tracker = r.rand(1000...99999)


        list_of_systems = systems.split(",")

        list_of_systems.each do |system|
        
        	Agentless.create(:tracker => tracker, scan => scan_name) # -- FIXME 
          
          Scan.run_scan(scan_type, profile, tracker, system, scan_name) # -- run the scan

          Scan.create(:scan_name => scan_name, :profile => profile, :system => system, :tracker => tracker)

          System.create(:scan_name => scan_name, :domain => @profile.domain, :ip => system, :status => '-1', :tracker => tracker, :profile => profile, :control => 'running', :scantype => @profile.scantype)
        end

        render :text => "OK"
     end

     def get_last_scan
        @last_scan = Scan.last

        render :text => @last_scan.tracker
     end
   end
end
